package web.service.impls;

import java.util.List;

import map.beans.OwfLibLocationBean;
import map.constants.MapDefaultPropertyValues;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import web.dao.interfaces.OwfLibLocationDao;
import web.service.interfaces.OwfLibLocationServiceInterface;

@Repository("owfLibService")
public class OwfLibLocationServiceImpl implements OwfLibLocationServiceInterface {
	private static Logger LOGGER = LoggerFactory.getLogger(OwfLibLocationServiceImpl.class);
	
	@Autowired
	OwfLibLocationDao owfLibDao;

	@Override
	/**
	 * 		This method is for testing purposes and scalability
	 * */
	public List<OwfLibLocationBean> findAll() {		
		List<OwfLibLocationBean> configs = owfLibDao.findAll();
		try {
			if (configs == null || configs.isEmpty()) {
				registerDefaultOwfLocation();
				configs = owfLibDao.findAll();
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}		
		return configs;
	}

	@Override
	public Long save(OwfLibLocationBean owf) {
		return owfLibDao.save(owf);
	}

	@Override
	public Long update(OwfLibLocationBean owf) {
		owf.setId(owfLibDao.getOwfLibLocationBean().getId());
		return owfLibDao.update(owf);
	}

	@Override
	public boolean delete(OwfLibLocationBean owf) {
		return owfLibDao.delete(owf);
	}

	@Override
	public OwfLibLocationBean getOwfLibLocationBean() {
		OwfLibLocationBean owf = owfLibDao.getOwfLibLocationBean();
		try {
			if (owf == null || owf.getLibLocation().equals("")) {
				owf = registerDefaultOwfLocation();
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}		
		return owf;	
	}

	private OwfLibLocationBean registerDefaultOwfLocation() {
		OwfLibLocationBean owf = new OwfLibLocationBean();
		owf.setLibLocation(MapDefaultPropertyValues.OWF_WIDGET_JS);
		owf.setId(save(owf));
		
		return owf;
	}

}
